import random
from io import BytesIO

from flask import request, jsonify, session, redirect, url_for, make_response
from werkzeug.security import generate_password_hash, check_password_hash

from models import db
from models.index import User
# from utils.captcha1.captcha_util import create_code
from utils.sms_aliyun import send_msg
from . import passport_blu


@passport_blu.route("/register", methods=["GET", "POST"])
def register():
    mobile = request.json.get('mobile')
    password = request.json.get('password')
    image_code = request.json.get('image_code').upper()
    smscode = request.json.get('smscode')
    # print(session['img'])
    # print(mobile, password, image_code, smscode)
    # if image_code != session['img']:

    # 校验"图片验证码"是否正确
    if session.get("sms_code") != smscode:
        ret = {
            "errno": 1003,
            "errmsg": "重新输入手机验证码"
        }
        return jsonify(ret)
    if db.session.query(User).filter(User.mobile == mobile).first():
        return jsonify({
            "errno": 1001,
            "errmsg": "已经注册..."
        })

    user = User()
    user.nick_name = mobile
    # user.password_hash = password
    # 生成加密的密码
    user.password_hash = generate_password_hash(password)
    user.mobile = mobile
    try:
        db.session.add(user)
        db.session.commit()
        ret = {
            "errno": 0,
            "errmsg": "注册成功..."
        }
        # 注册成功之后，立刻认为登录成功，也就说需要进行状态保持
        session['user_id'] = user.id
        session['nick_name'] = mobile
    except Exception as ret:
        print('------', ret)
        db.session.rollback()
        ret = {
            "errno": 1002,
            "errmsg": "注册失败..."
        }
    return jsonify(ret)


@passport_blu.route("/login", methods=["GET", "POST"])
def login():
    mobile = request.json.get("mobile")
    password = request.json.get("password")
    user = db.session.query(User).filter(User.mobile == mobile, User.password_hash == password).first()
    print(user.password_hash)
    print(password)
    if user:
        ret = {
            "errno": 0,
            "errmsg": "登录成功"
        }
        session['user_id'] = user.id
        session['nick_name'] = mobile
    else:
        ret = {
            "errno": 2001,
            "errmsg": "用户名或密码错误"
        }
    return jsonify(ret)


@passport_blu.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('index.index'))


@passport_blu.route('/image_code')
def image_code():
    """
    生成验证码
    """
    # code_str, image = create_code()
    # buf = BytesIO()  # 生成一个存到二进制数据的对象
    # # 把图片数据保存到buf里
    # image.save(buf, 'jpeg')
    # # 从bug里获取到图片的二进制数据
    # img_data = buf.getvalue()
    #
    # #  创建response对象 可以接收二进制数据或者字符串
    # ret = make_response(img_data)
    # # 释放buf内存数据
    # buf.close()
    # ret.headers['Content-Type'] = 'image/jpg'
    # session['img'] = code_str.upper()
    # return ret
    # 读取一个图片
    # with open("./yanzhengma.png", "rb") as f:
    #     image = f.read()

    # 真正的生成一张图片数据
    from utils.captcha.captcha import captcha

    # 生成验证码
    # hash值  验证码值  图片内容
    name, text, image = captcha.generate_captcha()

    # print("刚刚生成的验证码：", text)
    session['img'] = text
    # 返回响应内容
    resp = make_response(image)
    return resp


@passport_blu.route("/smscode", methods=["POST"])
def smscode():
    # 1. 提取数据
    image_code = request.json.get("image_code")
    mobile = request.json.get("mobile")

    # 2. 校验图片验证码是否正确
    image_code_session = session.get("img")
    print("输入的验证码", image_code)
    print("生成的验证码", image_code_session)
    if image_code.lower() != image_code_session.lower():
        ret = {
            "errno": 4004,
            "errmsg": "图片验证码错误..."
        }
        return jsonify(ret)

    # 3. 生成一个随机的6位数
    sms_code = str(random.randint(100000, 999999))
    print("短信验证码是:", sms_code)

    # 4. 存储到session中
    session['sms_code'] = sms_code

    # 5. 通过短信发送这个6位数
    # send_msg(mobile, sms_code)
    ret = {
        "errno": 0,
        "errmsg": "发送短信验证码成功..."
    }

    return jsonify(ret)
